<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-setting"
          size="mini"
          @click="handleSetIndicator"
        >设置指标
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="partnerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true"/>

      <el-table-column label="描述" align="center" prop="remark" :show-overflow-tooltip="true"/>

      <el-table-column label="排序号" align="center" prop="sortNum"/>

      <el-table-column label="更新时间" align="center" prop="updateTime" width="180"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合作伙伴对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号" prop="sortNum">
              <el-input-number v-model="form.sortNum" :min="0" :max="99999999" controls-position="right" placeholder="越大越靠前" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="描述" prop="remark">
              <el-input type="textarea" :rows="3" v-model="form.remark" placeholder="请输入描述" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 图片上传 -->
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="图片">
              <el-upload
                :action="uploadAction"
                list-type="picture-card"
                :limit="1"
                :file-list="imageFileList"
                :headers="uploadHeaders"
                :on-success="onImageUploadSuccess"
                :on-remove="onImageUploadRemove"
                :on-error="onImageUploadError"
                :before-upload="onBeforeUpload"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <div class="el-upload__tip" slot="tip">支持jpg/png文件，且不超过5MB，只能上传1张图片</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设置指标对话框 -->
    <el-dialog title="设置合作伙伴指标" :visible.sync="indicatorOpen" width="900px" append-to-body>
      <el-form ref="indicatorForm" :model="indicatorForm" :rules="indicatorRules" label-width="120px">
        <div class="metrics-container">
          <div class="metrics-header">
            <span class="metrics-title">合作伙伴指标</span>
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="addIndicator">添加指标</el-button>
          </div>

          <div v-if="indicatorForm.indicators && indicatorForm.indicators.length > 0" class="metrics-list">
            <div v-for="(indicator, index) in indicatorForm.indicators" :key="index" class="metric-item">
                             <el-row :gutter="16">
                 <el-col :xs="24" :sm="7">
                   <el-form-item :label="'指标值'" :prop="'indicators.' + index + '.value'" :rules="{ required: true, message: '指标值不能为空', trigger: 'blur' }">
                     <el-input v-model="indicator.value" placeholder="如：100+" />
                   </el-form-item>
                 </el-col>
                 <el-col :xs="24" :sm="11">
                   <el-form-item :label="'指标描述'" :prop="'indicators.' + index + '.label'" :rules="{ required: true, message: '指标描述不能为空', trigger: 'blur' }">
                     <el-input v-model="indicator.label" placeholder="如：合作伙伴数量" />
                   </el-form-item>
                 </el-col>
                 <el-col :xs="24" :sm="6">
                   <el-form-item label="操作">
                     <el-button
                       type="danger"
                       size="mini"
                       icon="el-icon-delete"
                       @click="removeIndicator(index)"
                       :disabled="indicatorForm.indicators.length <= 1"
                     >删除</el-button>
                   </el-form-item>
                 </el-col>
               </el-row>
            </div>
          </div>

          <div v-else class="metrics-empty">
            <el-empty description="暂无指标数据，请点击添加指标"></el-empty>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitIndicatorForm">确 定</el-button>
        <el-button @click="cancelIndicator">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPartner, addPartner, updatePartner, delPartner } from "@/api/official/partner"
import { getToken } from "@/utils/auth"
import request from "@/utils/request"

export default {
  name: "Partner",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合作伙伴表格数据
      partnerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        sortNum: [
          { required: true, message: "排序号不能为空", trigger: "blur" }
        ]
      },
      // 上传相关
      uploadAction: process.env.VUE_APP_BASE_API + '/system/file/upload',
      uploadHeaders: { Authorization: 'Bearer ' + getToken() },
      imageFileList: [],
      // 指标相关
      indicatorOpen: false,
      indicatorForm: {
        indicators: []
      },
      indicatorRules: {
        indicators: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!this.indicatorForm.indicators || this.indicatorForm.indicators.length === 0) {
                callback(new Error('至少需要添加1个指标'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询合作伙伴列表 */
    getList() {
      this.loading = true
      listPartner(this.queryParams).then(response => {
        this.partnerList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        remark: undefined,
        sortNum: 0,
        picFileId: null
      }
      this.imageFileList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加合作伙伴"
    },
    /** 设置指标按钮操作 */
    handleSetIndicator() {
      this.resetIndicatorForm()
      this.getIndicatorList()
      this.indicatorOpen = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      // 直接从列表行数据中获取字段信息，不调用详情接口
      this.form = {
        id: row.id,
        name: row.name,
        remark: row.remark,
        sortNum: row.sortNum,
        picFileId: row.picFileId,
        picFileUrl: row.picFileUrl
      }
      // 处理图片回显
      if (this.form.picFileUrl) {
        this.imageFileList = [{
          name: '合作伙伴图片',
          url: this.form.picFileUrl,
          uid: this.form.picFileId
        }]
      }
      this.open = true
      this.title = "修改合作伙伴"
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理图片文件ID - 只取第一个图片的ID
          this.form.picFileId = this.imageFileList.length > 0 ? this.imageFileList[0].uid : null

          if (this.form.id != undefined) {
            updatePartner(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPartner(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除合作伙伴编号为"' + ids + '"的数据项？').then(function() {
        return delPartner(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    // 图片上传前校验
    onBeforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isImage) {
        this.$modal.msgError('只能上传图片文件!')
        return false
      }
      if (!isLt5M) {
        this.$modal.msgError('图片大小不能超过 5MB!')
        return false
      }
      return true
    },
    // 图片上传成功
    onImageUploadSuccess(res) {
      if (res && res.code === 200 && res.data) {
        this.imageFileList.push({
          name: res.data.originalName,
          url: res.data.fullPath,
          uid: res.data.id
        })
      } else {
        this.$modal.msgError(res && res.msg ? res.msg : '上传失败')
      }
    },
    // 图片上传失败
    onImageUploadError() {
      this.$modal.msgError('上传失败，请重试')
    },
    // 图片移除
    onImageUploadRemove(file) {
      const index = this.imageFileList.findIndex(item => item.uid === file.uid)
      if (index > -1) {
        this.imageFileList.splice(index, 1)
      }
    },
    // 指标相关方法
    // 重置指标表单
    resetIndicatorForm() {
      this.indicatorForm = {
        indicators: []
      }
      this.resetForm("indicatorForm")
    },
    // 获取指标列表
    getIndicatorList() {
      request.get('/official/partner/listIndicator').then(response => {
        if (response && response.code === 200) {
          this.indicatorForm.indicators = response.data || []
        } else {
          this.indicatorForm.indicators = []
        }
      }).catch(() => {
        this.indicatorForm.indicators = []
      })
    },
    // 提交指标表单
    submitIndicatorForm() {
      this.$refs["indicatorForm"].validate(valid => {
        if (valid) {
          request.post('/official/partner/saveIndicator', this.indicatorForm.indicators).then(response => {
            if (response && response.code === 200) {
              this.$modal.msgSuccess("指标保存成功")
              this.indicatorOpen = false
            } else {
              this.$modal.msgError(response.msg || "保存失败")
            }
          }).catch(() => {
            this.$modal.msgError("保存失败")
          })
        }
      })
    },
    // 取消指标设置
    cancelIndicator() {
      this.indicatorOpen = false
      this.resetIndicatorForm()
    },
    // 添加指标
    addIndicator() {
      if (!this.indicatorForm.indicators) {
        this.$set(this.indicatorForm, 'indicators', [])
      }
      this.indicatorForm.indicators.push({
        value: '',
        label: ''
      })
      // 触发表单验证
      this.$nextTick(() => {
        this.$refs.indicatorForm.validateField('indicators')
      })
    },
    // 删除指标
    removeIndicator(index) {
      if (this.indicatorForm.indicators.length <= 1) {
        this.$modal.msgError('至少需要保留1个指标');
        return;
      }
      this.indicatorForm.indicators.splice(index, 1)
      // 触发表单验证
      this.$nextTick(() => {
        this.$refs.indicatorForm.validateField('indicators')
      })
    }
  }
}
</script>

<style scoped>
.el-upload__tip {
  line-height: 1.2;
  margin-top: 5px;
  color: #909399;
}

.metrics-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
}

.metrics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.metrics-title {
  font-weight: bold;
  color: #303133;
}

.metrics-list {
  margin-bottom: 16px;
}

.metric-item {
  background: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 12px;
  width: 100%;
}

.metric-item .el-row {
  margin: 0 !important;
}

.metric-item .el-col {
  padding: 0 8px;
}

.metric-item:last-child {
  margin-bottom: 0;
}

.metrics-empty {
  text-align: center;
  padding: 20px;
  color: #909399;
}
</style>
